import {Component, ChangeDetectorRef, ViewEncapsulation, OnInit, ViewChild, Input} from '@angular/core';

import {Http, Response} from '@angular/http';
import {ModalDirective} from 'ng2-bootstrap';
import {Router} from '@angular/router';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
import {VulModal} from './default-modal/default-modal.component';
import {Vul} from '../../domain/vul';
import {VulsService} from '../../services/vul-service';
import {Vultype} from '../../domain/vultype';
import {Vullevel} from '../../domain/vullevel';
import {NgUploaderOptions} from 'ngx-uploader/src/classes/ng-uploader-options.class';
import {SearchingModal} from './searching-modal';

@Component({
  selector: 'vul-list',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './vul-list.html',
  styleUrls: ['vul-list.scss'],
})

export class Vullist implements OnInit {

  @ViewChild('childModal') childModal: ModalDirective;

  baseUrl = 'http://127.0.0.1:8080/api/showvuls/';
  public fileUploaderOptions: NgUploaderOptions = {
    // url: 'http://website.com/upload'
    url: this.baseUrl + 'upload',
  };


  @Input()
  selectedvul = new Vul();
  originalvul: Vul;


  vuls: Vul[];

  selectedvultype = new Vultype();
  selectedvullevel = new Vullevel();
  vultype = new Vultype();
  vullevel = new Vullevel();

  vultypes: Vultype[];
  vullevels: Vullevel[];

  activeModal;
  searchingModal;
  vuldetail: Vul[];
  title = '';
  cveId = '';
  url = '';
  publishTime = '';
  updateTime = '';
  effectSys = '';
  message = '';
  poc = '';
  vendorPatch = '';
  type = '';
  level = '';
  typeid: number = 1;
  levelid: number = 1;
  types = [];
  levels = [];
  levelids = [];
  typeids = [];
  statu = 'ok';

  totalnumbers = [];
  selectedpage: number;

  page: number = 0;
  size: number = 10;
  sort: string = 'publishTime';

  disabled: boolean;
  disabled1: boolean;
  searching = '查询';

  minDate: Date;
  maxDate: Date;
  cn: any;

  showAll: boolean = true;


  public totalItems: number;
  public currentPage: number;
  public smallnumPages: number = 0;
  public itemsPerPage: number = 10;
  public maxSize: number = 5;
  public currentpage: number = 0;
  public numbers = [5, 10, 15, 20];


  constructor(private modalService: NgbModal, private vulservice: VulsService,
              private http: Http, private router: Router, private cdr: ChangeDetectorRef) {
    this.disabled = true;
    this.disabled1 = true;

    this.selectedvul.title = '';
    this.selectedvul.cveId = '';
    this.selectedvul.url = '';
    this.selectedvul.publishTime = '';
    this.selectedvul.updateTime = '';
    this.selectedvul.effectSys = '';
    this.selectedvul.message = '';
    this.selectedvul.poc = '';
    this.selectedvul.vendorPatch = '';
    this.selectedvul.typeid = 1;
    this.selectedvul.levelid = 1;
    this.selectedvultype.type = '';
    this.selectedvullevel.level = '';


  }


  getvulbyvulid(id: number): void {
    this.vulservice.getVulsbyId(id).subscribe(data => this.vuldetail = data.json(),
      error => console.log(error), () => console.log('获取到端口和协议'));
  }


  getvultype(): void {
    this.vulservice.getVultypesbyNoParam().subscribe(data => {
        this.vultypes = data.json();

      }
      , error => console.log(error), () => console.log('获取到漏洞类型'));

  }

  getvullevel(): void {
    this.vulservice.getVullevelsbyNoParam().subscribe(data => {
        this.vullevels = data.json();

      }
      , error => console.log(error), () => console.log('获取到漏洞危害程度'));

  }


  ngOnInit(): void {
    this.searchAll();
    this.getvultype();
    this.getvullevel();


    this.cn = {
      firstDayOfWeek: 1,
      dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],

      dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      /*monthNamesShort: [ "ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic" ]*/
    };


    const today = new Date();
    const month = today.getMonth();
    const year = today.getFullYear();
    const prevMonth = (month === 0) ? 11 : month - 1;
    const prevYear = (prevMonth === 11) ? year - 1 : year;
    const nextMonth = (month === 11) ? 0 : month + 1;
    const nextYear = (nextMonth === 0) ? year + 1 : year;
    this.minDate = new Date();
    this.minDate.setMonth(prevMonth);
    this.minDate.setFullYear(prevYear);
    this.maxDate = new Date();
    this.maxDate.setMonth(nextMonth);
    this.maxDate.setFullYear(nextYear);
  }

  getvulbynopage(): void {

    let publishTime = null;
    let updateTime = null;
    if (this.publishTime != '') {
      publishTime = this.formaDateTime(this.publishTime);
    } else {
      publishTime = this.publishTime;
    }
    if (this.updateTime != '') {
      updateTime = this.formaDateTime(this.updateTime);
    } else {
      updateTime = this.updateTime;
    }

    this.vulservice.getVulsWithNoPage(this.url, this.title, this.cveId, publishTime, updateTime, this.effectSys, this.message, this.poc, this.vendorPatch, this.typeid).subscribe(data => {
        this.totalItems = data.json().totalElements;
        this.currentPage = data.json().number + 1;
        this.vuls = data.json().content;
        for (let i = 0; i < data.json().totalPages; i++) {
          this.totalnumbers[i] = i + 1;
        }
        this.cdr.detectChanges();
      },
      error => console.log(error), () => console.log('获取到所有的vul'));
  }

  getvul(): void {

    //this.searchingModal = this.modalService.open(SearchingModal, {size: 'sm'});
    this.searching = '正在查询中....';
    let publishTime = null;
    let updateTime = null;
    if (this.publishTime != '') {
      publishTime = this.formaDateTime(this.publishTime);
    } else {
      publishTime = this.publishTime;
    }
    if (this.updateTime != '') {
      updateTime = this.formaDateTime(this.updateTime);
    } else {
      updateTime = this.updateTime;
    }


    this.vulservice.getVuls(this.url, this.title, this.cveId, publishTime, updateTime,
      this.effectSys, this.message, this.poc,
      this.vendorPatch, this.levelid, this.typeid,
      this.currentpage, this.itemsPerPage, this.sort).subscribe(data => {
        this.totalItems = data.json().totalElements;
        this.currentPage = data.json().number + 1;
        this.vuls = data.json().content;
        this.totalnumbers = [];
        for (let i = 0; i < data.json().totalPages; i++) {
          this.totalnumbers[i] = i + 1;
        }
        this.cdr.detectChanges();

      },
      error => console.log(error), () => {
        //this.searchingModal.close();
        this.searching = '查询';
        console.log('获取到满足条件的vul');
      });
  }


  showChildModal(item: Vul): void {


    this.activeModal = this.modalService.open(VulModal, {size: 'lg'});
    this.activeModal.componentInstance.disabled = true;
    this.activeModal.componentInstance.disabled1 = true;
    this.activeModal.componentInstance.selectedvul = item;
    this.activeModal.componentInstance.originalvul = item;

    //activeModal.componentInstance.modalTitle = item.title;
  }


  editChildModal(item: Vul): void {
    //const activeModal = this.modalService.open(VulModal, {size: 'lg'});
    this.activeModal = this.modalService.open(VulModal, {size: 'lg'});
    this.activeModal.componentInstance.disabled = false;
    this.activeModal.componentInstance.disabled1 = false;
    this.activeModal.componentInstance.selectedvul = item;
    this.activeModal.componentInstance.originalvul = item;


  }


  hideChildModal(): void {
    //const activeModal = this.modalService.open(VulModal, {size: 'lg'});
    this.activeModal.componentInstance.disabled = true;

    // this.childModal.hide();
  }


  edit(): void {
    const activeModal = this.modalService.open(VulModal, { size: 'lg' });
    activeModal.componentInstance.disabled1 = false;
    activeModal.componentInstance.disabled = false;
  }


  delete(item: Vul): void {
    if (window.confirm('确认要删除吗')) {
      this.vulservice.deleteVul(item.id).subscribe((res: Response) => {
          alert('删除成功');
          if (this.showAll) {
            this.searchAll();
          } else {
            this.getvul();
          }
        },
        error => {
          alert('删除失败');
          console.log(error);
        },
        () => console.log(item.cveId + ' 此对象已经删除'));
    }
  }


  public pageChanged(event: any): void {
    this.currentpage = event.page - 1;
    if (this.showAll) {
      this.searchAll();
    } else {
      this.getvul();
    }
  }

  onChange(): void {
    if (this.showAll) {
      this.searchAll();
    } else {
      this.getvul();
    }
  }

  search(): void {
    this.showAll = false;
    this.currentpage = 0;
    this.getvul();
  }

  searchAll() {
    this.title = '';
    this.cveId = '';
    this.url = '';
    this.publishTime = '';
    this.updateTime = '';
    this.effectSys = '';
    this.message = '';
    this.poc = '';
    this.vendorPatch = '';
    this.type = '';
    this.level = '';
    this.typeid = 1;
    this.levelid = 1;
    this.vulservice.getAllVuls(this.currentpage, this.itemsPerPage, this.sort).subscribe(data => {
        this.totalItems = data.json().totalElements;
        this.currentPage = data.json().number + 1;
        this.vuls = data.json().content;
        this.totalnumbers = [];
        for (let i = 0; i < data.json().totalPages; i++) {
          this.totalnumbers[i] = i + 1;
        }
        this.cdr.detectChanges();
      },
      error => console.log(error), () => console.log('获取到所有的vul'));


  }

  setpage(): void {
    this.currentpage = this.selectedpage - 1;
    if (this.showAll) {
      this.searchAll();
    } else {
      this.getvul();
    }
  }

  toExcel(): void {


    //let url="http://localhost:8080/api/vul/getvul/title="+this.title+"&cveId="+this.cveId+"&publishTime="+this.publishTime+"&updateTime="+this.updateTime+"&effectSys="+this.effectSys+"&message="+this.message+"&poc="+this.poc+"&vendorPatch="+this.vendorPatch+"&typeid="+this.typeid;
    const url = this.baseUrl + 'toExcel';
    console.log(url);
    window.open(url);

    ///getvul/title={title}&cveId={cveId}&publishTime={publishTime}&updateTime={updateTime}&effectSys={effectSys}&message={message}&poc={poc}&vendorPatch={vendorPatch}&typeid={typeid}

  }

  download(): void {


    //let url="http://localhost:8080/api/vul/getvul/title="+this.title+"&cveId="+this.cveId+"&publishTime="+this.publishTime+"&updateTime="+this.updateTime+"&effectSys="+this.effectSys+"&message="+this.message+"&poc="+this.poc+"&vendorPatch="+this.vendorPatch+"&typeid="+this.typeid;
    const url = this.baseUrl + 'download';
    console.log(url);
    window.open(url);
    this.getvullevel();
    this.getvultype();
    if (this.showAll) {
      this.searchAll();
    } else {
      this.getvul();
    }

    ///getvul/title={title}&cveId={cveId}&publishTime={publishTime}&updateTime={updateTime}&effectSys={effectSys}&message={message}&poc={poc}&vendorPatch={vendorPatch}&typeid={typeid}

  }

  formaDateTime(date): string {
    const y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    //var h = date.getHours();
    //h=h < 10 ? ('0' + h) : h;
    //var minute = date.getMinutes();
    //minute = minute < 10 ? ('0' + minute) : minute;
    //var second=date.getSeconds();
    //second=second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d; /*+' '+h+':'+minute+':'+second*/
  }


}
